package edu.nf.vac.api.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import edu.nf.vac.api.vo.ResultVO;
import edu.nf.vac.auth.inf.UserTokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @author LQJ
 * @date 2022/3/30
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";
    @DubboReference(interfaceClass = UserTokenService.class,
            version="1.0.0", check = false)
    private UserTokenService tokenService;
    public boolean perHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String tokenHeader = request.getHeader(TOKEN_HEADER);
        if(tokenHeader != null) {
            //解析Token时将“Bearer ”前缀去掉
            String jwt = tokenHeader.replace(TOKEN_PREFIX, "");
            try {
                Integer uid = tokenService.verify(jwt);
                request.setAttribute("uid", uid);
                return true;
            } catch (Exception e) {
                log.error(e.getMessage());
                responseView(response, "用户会话已失效");
            }
        }else{
            responseView(response, "请先登陆小程序");
        }
        return false;
    }
    /**
     * 响应视图
     * @param response
     * @param message
     * @throws IOException
     */
    private void responseView(HttpServletResponse response, String message) throws IOException {
        ResultVO vo = new ResultVO();
        vo.setCode(HttpStatus.UNAUTHORIZED.value());
        vo.setMessage(message);
        response.setContentType("application/json;charset=utf-8");
        String json = new ObjectMapper().writeValueAsString(vo);
        response.getWriter().println(json);
    }

}
